package com.ruoyi.project.comp.juror;


import com.github.pagehelper.Page;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.post.service.IPostService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.score.domain.CompScore;
import com.ruoyi.project.system.score.service.ICompScoreService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户信息管理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/comp/juror")
public class JurorController extends BaseController {
    private String prefix = "comp/juror";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ICompScoreService compScoreService;

    /**
     * 跳转客户列表页面
     */
    @GetMapping()
    public String juror() {
        return prefix + "/juror";
    }

    /**
     * 客户列表查询（默认筛选usertype=03的客户数据）
     */
    // @RequiresPermissions("comp:juror:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user) {
        startPage();
        CompScore compScore = new CompScore();
        List<CompScore> scoreList = compScoreService.selectCompScoreList(compScore);
        List<User> list = userService.selectJurorList(user);
        for (int i = 0; i < list.size() ; i++) {
            User useri = list.get(i);
            int count = 0;
            List<CompScore> scoreListi = scoreList.stream().filter(s ->
                    s.getUserId().intValue() == useri.getUserId().intValue())
                    .collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(scoreListi)){
                count = scoreListi.size();
                scoreListi.sort(new Comparator<CompScore>() {
                    @Override
                    public int compare(CompScore o1, CompScore o2) {
                        return (int) (o1.getId() - o2.getId());
                    }
                });
                Date date = scoreListi.get(0).getCreateTime();
                if(date != null){
                    useri.setLastScoreTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
                }
                useri.setScoreCount(count +"");
            }

        }
        return getDataTable(list);
    }


    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(User user) {
        // 1. 校验权限
//        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
        // 2. 校验该记录是否为管理员（usertype=01）
        User admin = userService.selectUserById(user.getUserId());
        if (admin == null || !"02".equals(admin.getUserType())) {
            return error("操作失败，仅允许修改管理员状态");
        }
        // 3. 执行状态修改，强制保留管理员类型
        user.setUserType("02");
        return toAjax(userService.changeStatus(user));
    }



    @GetMapping("/scoreRecord/{userId}")
    public String getScoreRecord(@PathVariable("userId") Integer userId, ModelMap mmap) {
        startPage();
        CompScore compScore = new CompScore();
        compScore.setUserId(Long.valueOf(userId));

        User admin = userService.selectUserById(Long.valueOf(userId));
        if (admin == null || !"02".equals(admin.getUserType())) {
            mmap.put("userName", admin.getUserName());
        }

        List<CompScore> list = compScoreService.selectCompScoreList(compScore);
        mmap.put("data", list);
        return prefix + "/scoreRecord";
    }

    /**
     * 跳转新增管理员页面（移除部门相关数据）
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        // 仅传递角色和岗位数据，移除部门相关信息
        mmap.put("roles", roleService.selectRoleAll().stream()
                .filter(r -> !r.isAdmin())
                .collect(Collectors.toList()));
        return prefix + "/add";
    }

    /**
     * 新增保存管理员（自动设置usertype=01）
     */
    // @RequiresPermissions("comp:admin:add")
    @Log(title = "管理员管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated User user) {
        // 核心：新增管理员强制设置类型为01
        //user.setUserType("01");

        // 重复校验逻辑（与用户一致）
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user))) {
            return error("新增评委'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增评委'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增评委'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.insertUser(user));
    }

    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }


}
